const express = require("express");
const {
  createProxyMiddleware,
  responseInterceptor,
} = require("http-proxy-middleware");
const cors = require("cors");
// const cookieParser = require('cookie-parser')
// const path = require('path')
const { serverMap } = require("./server");
const xyhConfigRoutes = require("./routes/xyhConfigRoutes");

const app = express();

const port = 3000;

const targetList = [
  {
    // 页面商城
    target: "https://chdstore.web.sdo.com",
    prependPath: "/chdstore",
  },
  {
    target: "https://w.cas.sdo.com",
    prependPath: "/cas",
  },
  {
    // 等级补完
    target: "https://chdact2.web.sdo.com",
    prependPath: "/chdact2",
  },
  {
    // 统一团购
    target: "https://chdtuan.web.sdo.com",
    prependPath: "/chdtuan",
  },
];

// app.use(cookieParser())

const cookies =
  "Hm_lvt_e534c77c088e50378902b258dcb634c7=1722534881,1722535132,1722600053,1722663115; NSC_MC-dietupsf.xfc.tep.dpn-I80=ffffffff09884f0945525d5f4f58455e445a4a423660; ci_sessions=7449d5acf49ef99f80cfc0069dbbdd929452f2a2; userinfo=userid=622168341-1212991890-1722666456&siteid=SDG-08130-01; LAT=l=38&l_err=0; Hm_lpvt_e534c77c088e50378902b258dcb634c7=1722666479; __wftflow=0=3&132888210=2&635443455=2&1563907181=4&1701271933=2&1805592828=3; __wftflag=1; RT=ul=1722666483075&r=https%3A%2F%2Fchdstore.web.sdo.com%2FShop%2FCart&hd=1722666478653&cl=1722666482375&nu=javascript%3A";

app.use(
  cors({
    origin: true,
    credentials: true,
  })
);

function apiProxyHandle(item) {
  const { target, prependPath } = item;
  return createProxyMiddleware({
    target,
    changeOrigin: true,
    selfHandleResponse: true,
    cookieDomainRewrite: "localhost",
    prependPath: {
      [`^${prependPath}`]: "",
    },
    on: {
      proxyReq: (proxyReq, req, res) => {
        // if (cookie) {
        //   proxyReq.setHeader('Cookie', cookie)
        // }
        // if (target === 'https://w.cas.sdo.com') {
        // } else {
        // }
        const referer = req.headers?.referer;
        proxyReq.setHeader("Referer", referer || target);
        // proxyReq.setHeader("cookie", cookies);

        // if (req.path.includes("Exchange")) {
        //   proxyReq.setHeader("sec-fetch-dest", "document");
        //   proxyReq.setHeader("sec-fetch-mode", "navigate");
        //   proxyReq.setHeader("sec-fetch-site", "same-origin");
        //   proxyReq.setHeader("sec-fetch-user", "?1");
        // }
      },

      proxyRes: responseInterceptor(
        async (responseBuffer, proxyRes, req, res) => {
          // const originalSetCookie = proxyRes.headers['set-cookie']

          // if (originalSetCookie) {
          //   const modifiedSetCookie = originalSetCookie.map(c =>
          //     c.replace(/Domain=[^;]*/g, 'Domain=localhost')
          //   )
          //   // cookie = modifiedSetCookie
          //   proxyRes.headers['set-cookie'] = modifiedSetCookie
          // }

          const commentRegex = /<!--(.*?)-->/gs;
          let response = responseBuffer.toString("utf8");
          // 过滤注释
          response = response.replace(commentRegex, "");
          const path = Object.keys(serverMap).find((key) => {
            return req.path.includes(key);
          });

          console.log(req.path, path);
          if (path) {
            return serverMap[path]({ proxyRes, req, res, response });
          } else {
            return responseBuffer;
          }
        }
      ),

      // error: (err, req, res) => {
      //   console.log(123)
      // }
    },
  });
}

targetList.forEach((item) => {
  app.use(item.prependPath, apiProxyHandle(item));
});

// app.use(express.static(path.join(__dirname, 'public')))

// app.get('/home', (req, res) => {
//   res.sendFile(path.join(__dirname, 'public', 'index.html'))
// })

app.use("/xyh/config", express.json({limit: '10mb'}), xyhConfigRoutes);

app.listen(port, () => {
  console.log(`http://localhost:${port}`);
});
